package org.example.seckill.service;

import org.example.seckill.bean.goods;
import org.example.seckill.bean.seckillGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author woopsion
 * @date 2025-07-05
 */
@Service
public class RedisWithGoodsInfoService {
    @Autowired
    private goodsService goodsService;
    @Autowired 
    private seckillGoodsService sgs;
    @Resource
    private RedisTemplate redisTemplate;


    /**
     * redis缓存作为加速
     * 过期时间为60秒
     * 过期之后无对象，sql 查询对应信息， 如果无返回空
     * @param goodsId
     * @return
     */
    public goods getGoods(Long goodsId){
        goods gs = (goods)redisTemplate.opsForValue().get("goods:detail:" + goodsId);
        if (gs == null){
            gs= goodsService.getById(goodsId);
            if (gs==null){return null;}
            redisTemplate.opsForValue().set("goods:detail:" + goodsId,gs,60, TimeUnit.SECONDS);
        }
        return gs;
    }
    
    public seckillGoods getseckillGoods(Long goodsId){
        seckillGoods gs_kill = (seckillGoods)redisTemplate.opsForValue().get("goods:detail:seckill:" + goodsId);
        if (gs_kill == null){
            gs_kill= sgs.getById(goodsId);
            if (gs_kill==null){return null;}
            redisTemplate.opsForValue().set("goods:detail:seckill:" + goodsId,gs_kill,60, TimeUnit.SECONDS);
        }
        return gs_kill;
    }

}
